const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const paths = require('./paths');
const publicPath = paths.servedPath;
const publicUrl = publicPath.slice(0, -1);
const env = require('./env')(publicUrl);

if (env.stringified['process.env'].NODE_ENV !== '"production"') {
	throw new Error('Production builds must have NODE_ENV=production.');
}
if (!env.stringified['process.env'].REACT_APP_API_SERVER) {
	throw new Error('Producition Must set REACT_APP_API_SERVER!');
}

console.log('env', env.stringified);
module.exports = {
	// Don't attempt to continue if there are any errors.
	bail: true,
	entry: [require.resolve('./polyfills'), paths.appIndexJs],
	// entry: [require.resolve('./polyfills')],
	output: {
		path: paths.appBuild,
		filename: 'static/js/[name].js',
		chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
		// We inferred the "public path" (such as / or /my-project) from homepage.
		publicPath: publicPath,
		// Point sourcemap entries to original disk location (format as URL on Windows)
		devtoolModuleFilenameTemplate: info =>
			path
				.relative(paths.appSrc, info.absoluteResourcePath)
				.replace(/\\/g, '/'),
	},
	resolve: {
		modules: ['node_modules'].concat(
			process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
		),
		extensions: ['.js', '.json', '.jsx'],
		plugins: [],
	},
	module: {
		strictExportPresence: true,
		rules: [
			{
				oneOf: [
					{
						test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
						loader: require.resolve('url-loader'),
						options: {
							limit: 10000,
							name: 'static/media/[name].[hash:8].[ext]',
						},
					},
					// Process JS with Babel.
					{
						test: /\.(js|jsx|mjs)$/,
						loader: require.resolve('babel-loader'),
						include: [paths.appSrc, path.resolve('./node_modules/mobx')],
						options: {
							cacheDirectory: true,
							compact: true,
							presets: ['react-app'],
							plugins: [
								['import', { libraryName: 'antd', style: 'css' }],
								'transform-es2015-arrow-functions',
								'transform-es2015-parameters',
								'transform-decorators-legacy',
								'transform-object-rest-spread',
								'transform-remove-console',
							],
						},
					},
					//注：我们自己不写css，因此只有第3方库有css，它们的css不使用module(antd)
					{
						test: /\.css$/,
						use: [
							require.resolve('style-loader'),
							require.resolve('css-loader'),
						],
					},
					//我们自己只写less，且必须使用module
					{
						test: /\.less$/,
						use: [
							require.resolve('style-loader'),
							{
								loader: require.resolve('css-loader'),
								options: { modules: true },
							},
							{
								loader: require.resolve('less-loader'),
								options: { javascriptEnabled: true },
							},
						],
					},
					{
						loader: require.resolve('file-loader'),
						// Exclude `js` files to keep "css" loader working as it injects
						// it's runtime that would otherwise processed through "file" loader.
						// Also exclude `html` and `json` extensions so they get processed
						// by webpacks internal loaders.
						exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
						options: {
							name: 'static/media/[name].[hash:8].[ext]',
						},
					},
				],
			},
		],
	},
	plugins: [
		new CopyWebpackPlugin([{ from: 'public' }], { copyUnmodified: true }),
		new InterpolateHtmlPlugin(env.raw),
		new HtmlWebpackPlugin({
			inject: true,
			template: paths.appHtml,
			minify: {
				removeComments: true,
				collapseWhitespace: true,
				removeRedundantAttributes: true,
				useShortDoctype: true,
				removeEmptyAttributes: true,
				removeStyleLinkTypeAttributes: true,
				keepClosingSlash: true,
				minifyJS: true,
				minifyCSS: true,
				minifyURLs: true,
			},
		}),
		new webpack.DefinePlugin({ ...env.stringified }),
		new webpack.optimize.UglifyJsPlugin({
			// compress: { warnings: false, comparisons: false },
			compress: false,
			mangle: { safari10: true },
			output: { comments: false, ascii_only: true },
			sourceMap: false,
			cache: true,
			parallel: true,
		}),
	],
	node: {
		dgram: 'empty',
		fs: 'empty',
		net: 'empty',
		tls: 'empty',
		child_process: 'empty',
	},
};
